#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string>
using std::cout, std::endl, std::cerr;

bool GetQeryString(std::string& qery_string)
{
    std::string method = getenv("METHOD");
    cerr << "method: " << method << endl; 
    if(method == "GET"){
        qery_string = getenv("QUERY_STRING");
    }
    else if(method == "POST"){
        int content_length = atoi(getenv("CONTENT_LENGTH"));

        cerr << "content_length: " << content_length << endl;

        char c = '\0';
        while(content_length){
            if(read(0, &c, sizeof c) > 0){
                qery_string.push_back(c);
                --content_length;
            }
            else{
                return false;
            }
        }
    }
    else{
        return false;
    }
    return true;
}

bool CutString(const std::string& target, const std::string& sep, std::string& out1, std::string& out2){
    size_t pos = target.find(sep);
    if(pos == std::string::npos){
        return false;
    }
    out1 = target.substr(0, pos);
    out2 = target.substr(pos + sep.size());
    return true;
}

int main()
{
    cerr << "-----------------CGI BEGIN!--------------------" << endl;
    //cerr << "method: " << method << endl;
    std::string query_string;
    GetQeryString(query_string);
    cerr << "query_string: " << query_string << endl;

    std::string str1;
    std::string str2;
    CutString(query_string, "&", str1, str2);

    std::string name1;
    std::string value1;
    CutString(str1, "=", name1, value1);

    std::string name2;
    std::string value2;
    CutString(str2, "=", name2, value2);

    //1 
    std::cout << name1 << " : " << value1 << std::endl;
    std::cout << name2 << " : " << value2 << std::endl;

    //2
    std::cerr << name1 << " : " << value1 << std::endl;
    std::cerr << name2 << " : " << value2 << std::endl;
    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());

    //可能向进行某种计算(计算，搜索，登陆等)，想进行某种存储(注册)
    std::cout << "<html>";
    std::cout << "<head><meta charset=\"utf-8\"></head>";
    std::cout << "<body>";
    std::cout << "<h3> " << value1 << " + " << value2 << " = "<< x+y << "</h3>";
    std::cout << "<h3> " << value1 << " - " << value2 << " = "<< x-y << "</h3>";
    std::cout << "<h3> " << value1 << " * " << value2 << " = "<< x*y << "</h3>";
    std::cout << "<h3> " << value1 << " / " << value2 << " = "<< x/y << "</h3>";
    std::cout << "</body>";
    std::cout << "</html>";

    cerr << "-----------------CGI END!----------------------" << endl;
    return 0;
}